<template>
  <div class="gl_contentBox gl_heightFull" @click="cliclEmptyChange">
    <div class="change_admin change_super">
      <el-form ref="ChangeSuperTubeVO" class="gl_form_mini" :model="ChangeSuperTubeVO" :rules="ChangeSuperTubeVO_Rules" label-width="110px">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item :label="$t('configuration.selectChangeColleague')" prop="userName">
              <div style="position:relative">
                <div class="mock_input" :class="[collageListShow ? 'active' : '', mockInput]" @click.stop="changePullStatus">
                  <el-input v-model="ChangeSuperTubeVO.userName" type="text" size="mini" disabled />
                </div>
                <div class="icon_pull gl_clear" @click.stop="changePullStatus">
                  <span class="placeholder_info" :class="ChangeSuperTubeVO.userName==''? '':'placeholder_info_color' ">{{ ChangeSuperTubeVO.userName || $t('tenant.pleaseSelect') }}</span>
                  <i class="gl_fr" :class="iconClass" />
                </div>
              </div>
              <!-- 下拉列表 -->
              <div v-show="collageListShow" class="list_pull_style" @click.stop="collageListShow=true">
                <div class="all_info_box">
                  <div class="info_left">
                    <el-tree :data="organizationUnitsTree" :props="defaultProps" :expand-on-click-node="false" node-key="code" @node-click="handleNodeClick" />
                  </div>
                  <div v-loading="rightLoading" class="info_right">
                    <ul v-if="organizationUnitsUsers && organizationUnitsUsers.length>0">
                      <el-radio-group v-model="radio">
                        <li v-for="(data, index) in organizationUnitsUsers" :key="index" style="height:26px" @click.stop="getData(data)">
                          <el-radio :label="data.id">{{ data.name }}{{ "（" +data.phoneNumber+"）" }}</el-radio>
                        </li>
                      </el-radio-group>
                    </ul>
                    <div v-else style="width:90px" />
                  </div>
                </div>
                <div class="popper__arrow" />
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 短信验证 -->
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item :label="$t('configuration.getVerificationCode')" prop="code">
              <div>
                <el-input v-model="ChangeSuperTubeVO.code" class="verifycode_input" type="text" minlength="6" maxlength="6" size="mini" :placeholder="$t('rules.verifyCode')">
                  <el-button v-if="isSendMsg" slot="append" :loading="msgLoading" size="mini" style="width:90px" @click="showVerificationModel">
                    <span>{{ $t('register.sendMSG') }}</span>
                  </el-button>
                  <el-button v-else slot="append" size="mini" style="width:90px" class="noClick">
                    <span>{{ reSendTime }}(s)</span>
                  </el-button>
                </el-input>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="18">
            <el-button type="primary" class="new_super_submit" size="mini" @click="submitData('ChangeSuperTubeVO')">{{ $t('configuration.configurationSubmit') }}</el-button>
          </el-col>
        </el-row>
      </el-form>

      <el-dialog :title="changeHide? $t('configuration.changeSuperTube'):$t('configuration.changeSuccess')" class="gl_dialog_TitleLine" :visible.sync="dialogVisible" :show-close="changeHide? true: false" width="520px">
        <template v-if="changeHide">
          <div class="infomation_box">
            <p class="info_p_box">{{ $t('configuration.areYouOk') }}</p>
          </div>
          <span slot="footer" class="dialog-footer">
            <el-button size="mini" @click="changeCancel">{{ $t('button.cancel') }}</el-button>
            <el-button v-loading="submitLoading" type="primary" size="mini" @click="changeOK">{{ $t('table.confirm') }}</el-button>
          </span>
        </template>
        <template v-else>
          <div class="infomation_box">
            <span class="info_p_box">{{ $t('configuration.changeSuccess') }}</span>
            <!-- <span class="info_p_box">{{ $t('configuration.superHaveNew') }}[{{ radio }}]</span> -->
            <p>{{ downTime }}{{ $t('configuration.infoHide') }}</p>
          </div>
          <span slot="footer" class="dialog-footer">
            <el-button size="mini" style="visibility:hidden" @click="changeCancel">{{ $t('button.cancel') }}</el-button>
          </span>

        </template>
      </el-dialog>

    </div>
  </div>
</template>

<script>
import { ChangeSuperTubeVO } from '@/lib/form/configuration';
import { translateByCode } from '@/lib/getTransData';
import { ChangeSuperTubeVO_Rules } from '@/lib/validate/configuration/index.js';
import { judgeToLogout } from '@/lib/oidc_fun';
import {
  api_GET_OrganizationUnitsTree,
  api_GET_OrganizationUnitsIdUsers,
  api_POST_UsersChangeAdmin,
  api_POST_UsersChangeAdminSmsCode
} from '@/extend/api/swaggerApi/identity.js'; // api接口

export default {
  name: 'ChangeSuper',
  data() {
    return {
      ChangeSuperTubeVO: new ChangeSuperTubeVO(),
      ChangeSuperTubeVO_Rules: new ChangeSuperTubeVO_Rules(),
      dialogVisible: false, // 弹窗的显示与否
      isSendMsg: true, // 是否已经发送验证码
      downTime: 5, // 系统退出倒计时
      changeHide: true, // 提交时弹框的内容
      collageListShow: false, // 控制下拉列表的显示隐藏
      radio: '', // 储存选择用户的信息
      organizationUnitsUsers: [], // 下拉列表显示的人员
      // includeDetails: true,
      reSendTime: 0, // 验证码倒计时
      currentTreeDate: {}, // 获取树的组织架构
      iconClass: 'el-input__icon el-icon-arrow-down', // 下拉图标
      organizationUnitsTree: [], // 下拉列表左侧组织树结构
      defaultProps: {
        children: 'children',
        label: 'displayName'
      },
      rightLoading: false, // 下拉列表右侧的loading
      submitLoading: false, // 提交按钮的loading
      msgLoading: false, // 短信的loading
      mockInput: '', // 第一个表单框的边框颜色
      phoneNumber: '' // 获取选中的新同事的电话号码
    };
  },
  watch: {
    // 监听表单框内容，切换表单框颜色
    'ChangeSuperTubeVO.userName'(newVal) {
      this.mockInput = newVal ? '' : 'error';
      this.$refs.ChangeSuperTubeVO.validateField('userName');
    }
  },
  created() {
    this.getOrganizationUnitsTree();
  },
  methods: {
    // 获取组织树结构
    getOrganizationUnitsTree() {
      api_GET_OrganizationUnitsTree()
        .then(res => {
          this.organizationUnitsTree = res.items;
          // this.loading = false;
        })
        .catch(error => {
          // this.loading = false;
          this.$message({
            type: 'warning',
            message: error.error.message
          });
        });
    },
    // 点击树获取当前组织结构数据
    handleNodeClick(data) {
      this.currentTreeDate = data;
      this.getUserName();
    },
    // 点击radio获取表单框的元素
    getData(data) {
      this.ChangeSuperTubeVO.userName =
        data.name + '（' + data.phoneNumber + '）';
      this.radio = data.name;
      this.collageListShow = false;
      this.iconClass = 'el-input__icon el-icon-arrow-down';
      this.phoneNumber = data.phoneNumber;
    },
    // 获取用户列表
    getUserName() {
      this.rightLoading = true;
      const param = {
        isEnabled: true
      };
      api_GET_OrganizationUnitsIdUsers(this.currentTreeDate.id, param)
        .then(res => {
          this.organizationUnitsUsers = res.items;
          this.rightLoading = false;
        })
        .catch(error => {
          this.loading = false;
          this.rightLoading = true;
          this.$message({ type: 'error', message: error });
        });
    },
    // 获取验证码
    showVerificationModel() {
      if (this.ChangeSuperTubeVO.userName !== '') {
        // 调取发送验证码的接口。
        const param = {
          phoneNumber: this.phoneNumber
        };
        if (!this.phoneNumber) {
          this.$message({
            type: '请选择有手机号码的用户！',
            message: error
          });
          return;
        }
        this.msgLoading = true;
        api_POST_UsersChangeAdminSmsCode(param)
          .then(res => {
            this.msgLoading = false;
            this.isSendMsg = false;
            this.countDownTime(60);
          })
          .catch(error => {
            this.msgLoading = false;
            this.$message({
              type: 'warning',
              message: error.error.message
            });
          });
      } else {
        this.$message({
          showClose: true,
          message: translateByCode('configuration.pleaseSelect'),
          type: 'error'
        });
      }
    },
    // 短信倒计时
    countDownTime(num) {
      let timer = null;
      clearInterval(timer);
      this.isSendMsg = false;
      this.reSendTime = num;
      timer = setInterval(() => {
        this.isSendMsg = false;
        this.reSendTime -= 1;
        if (this.reSendTime <= 0) {
          clearInterval(timer);
          this.isSendMsg = true;
        }
      }, 1000);
    },
    setFalse() {
      this.changeHide = true;
    },
    // 退出系统提示提示倒计时
    downSystemTime(num) {
      let time = null;
      clearInterval(time);
      this.downTime = num;
      time = setInterval(() => {
        this.downTime -= 1;
        if (this.downTime <= 0) {
          clearInterval(time);
          this.dialogVisible = false;
          this.logout();
          setTimeout(() => {
            this.setFalse();
          }, 800);
        }
      }, 1000);
    },
    // 退出系统
    async logout() {
      const tenantId =
        this.$store.state.user.info && this.$store.state.user.info.tenantId
          ? this.$store.state.user.info.tenantId
          : '';
      await this.$store.dispatch('user/logout');
      judgeToLogout(
        window.location.origin +
          window.location.pathname +
          '#/?tenantid=' +
          tenantId
      );
    },
    // 点击图标
    changePullStatus() {
      if (this.iconClass === 'el-input__icon el-icon-arrow-down') {
        this.iconClass = 'el-input__icon el-icon-arrow-down is-reverse';
        this.collageListShow = true;
      } else {
        this.iconClass = 'el-input__icon el-icon-arrow-down';
        this.collageListShow = false;
      }
    },
    // 点击空白处收回下拉框
    cliclEmptyChange() {
      this.collageListShow = false;
      this.iconClass = 'el-input__icon el-icon-arrow-down';
    },
    // 提交数据
    submitData(formData) {
      this.$refs[formData].validate(valid => {
        if (valid) {
          // 调用确定更换的接口
          this.mockInput = '';
          this.dialogVisible = true;
        } else {
          if (this.ChangeSuperTubeVO.userName === '') {
            this.mockInput = 'error';
          }
        }
      });
    },
    // 确定更换
    changeOK() {
      this.submitLoading = true;
      const param = {
        phoneNumber: this.phoneNumber,
        code: this.ChangeSuperTubeVO.code
      };
      api_POST_UsersChangeAdmin(param)
        .then(res => {
          this.changeHide = false;
          this.submitLoading = false;
          this.downSystemTime(5);
        })
        .catch(error => {
          this.dialogVisible = false;
          this.submitLoading = false;
          this.$message({
            type: 'error',
            message: error.response.data.error.message
          });
          return false;
        });
    },
    // 取消更换
    changeCancel() {
      this.dialogVisible = false;
    }
  }
};
</script>

<style scoped>
.new_super_submit {
  width: 100%;
  margin-left: 110px;
}
.change_super {
  width: 400px;
}
.list_pull_style {
  position: absolute;
  z-index: 99;
  min-width: 420px;
  min-height: 150px;
  border: 1px solid #dfe4ed;
  background: #fff;
  padding: 10px 30px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border-radius: 4px;
  margin: 12px 0 5px 0;
  font-size: 14px;
  transition: all 0.3s linear;
}
.popper__arrow,
.popper__arrow::after {
  position: absolute;
  display: block;
  width: 0;
  height: 0;
  border-color: transparent;
  border-style: solid;
}
.popper__arrow {
  top: -12px;
  left: 35px;
  margin-right: 3px;
  border-top-width: 0;
  border-bottom-color: #e6ebf5;
}
.popper__arrow {
  border-width: 6px;
  -webkit-filter: drop-shadow(0 2px 12px rgba(0, 0, 0, 0.03));
  filter: drop-shadow(0 2px 12px rgba(0, 0, 0, 0.03));
}

.popper__arrow::after {
  content: ' ';
  border-width: 6px;
}
.popper__arrow::after {
  top: 1px;
  margin-left: -6px;
  border-top-width: 0;
  border-bottom-color: #ffffff;
}
.icon_pull {
  position: absolute;
  width: 100%;
  left: 0;
  color: #c0c4cc;
  top: -5px;
  cursor: pointer;
}
.placeholder_info {
  position: relative;
  top: 3px;
  left: 15px;
}
.placeholder_info_color {
  color: #000;
}
.all_info_box {
  display: flex;
  min-height: inherit;
}
.info_left {
  min-width: 260px;
  padding-right: 20px;
  overflow: hidden;
  overflow-x: auto;
  overflow-y: auto;
  height: 300px;
}
.info_left::-webkit-scrollbar {
  width: 3px;
  height: 3px;
}
.info_left::-webkit-scrollbar-thumb {
  border-radius: 10px;
  background: #aaabad;
}
.info_left::-webkit-scrollbar-track {
  border-radius: 0;
  background: #ebeef5;
}
.info_right {
  border-left: 1px solid #dfe4ed;
  padding-left: 20px;
  margin-left: 20px;
  min-width: 120px;
}

.mock_input {
  box-sizing: content-box;
  height: 0;
  width: 258px;
  padding: 26px 15px 0;
  border: 1px solid #dfe4ed;
  border-radius: 4px;
  overflow: hidden;
  cursor: pointer;
  transition: 0.3s;
}
.mock_input.active {
  border: 1px solid #1890ff;
}
.mock_input.error {
  border: 1px solid #ff4949;
}
.infomation_box {
  text-align: center;
  height: 60px;
  padding-top: 20px;
}
.info_p_box {
  font-size: 18px;
}
</style>

<style>
.change_super .el-input.is-disabled .el-input__inner {
  cursor: pointer;
  background: #ffffff;
  color: #000;
}

.change_super .el-icon-arrow-down.is-reverse {
  -webkit-transform: rotateZ(180deg);
  transform: rotateZ(180deg);
}
</style>
